// 答题系统JavaScript

// 题目数据（从服务器加载）
let questions = [];

let currentQuestionIndex = 0;
let userAnswers = [];
let timeElapsed = 0;
let timerInterval = null;

// 配置marked选项
if (typeof marked !== 'undefined') {
    marked.setOptions({
        breaks: true,
        gfm: true,
        sanitize: false
    });
}

// Markdown渲染辅助函数（支持数学公式）
function renderMarkdown(text) {
    if (!text) return '';
    if (typeof marked !== 'undefined') {
        return marked.parse(text);
    }
    return text;
}

// 渲染数学公式
function renderMath(element) {
    if (typeof window.renderMathInElement !== 'undefined' && typeof katex !== 'undefined') {
        try {
            window.renderMathInElement(element, {
                delimiters: [
                    {left: '$$', right: '$$', display: true},
                    {left: '$', right: '$', display: false},
                    {left: '\\[', right: '\\]', display: true},
                    {left: '\\(', right: '\\)', display: false}
                ],
                throwOnError: false
            });
        } catch (e) {
            console.warn('数学公式渲染失败:', e);
        }
    }
}

// ========== AI助手功能 ==========
// AI助手相关元素
const aiAssistantBtn = document.getElementById('aiAssistantBtn');
const aiChatPanel = document.getElementById('aiChatPanel');
const aiCloseBtn = document.getElementById('aiCloseBtn');
const aiChatInput = document.getElementById('aiChatInput');
const aiSendBtn = document.getElementById('aiSendBtn');
const aiChatMessages = document.getElementById('aiChatMessages');

// AI助手按钮拖动功能
if (aiAssistantBtn) {
    let isDragging = false;
    let startX, startY;
    let initialLeft, initialTop;
    let autoHideTimer = null;
    
    // 从localStorage加载保存的位置
    const savedPosition = localStorage.getItem('aiAssistantBtnPosition');
    let hasCustomPosition = false; // 标记是否有自定义位置
    
    if (savedPosition) {
        const { left, top } = JSON.parse(savedPosition);
        aiAssistantBtn.style.left = left;
        aiAssistantBtn.style.top = top;
        aiAssistantBtn.style.right = 'auto';
        aiAssistantBtn.style.bottom = 'auto';
        hasCustomPosition = true;
        // 加载后检查是否需要收缩（只有自定义位置才检查）
        setTimeout(() => checkEdgeAndHide(), 100);
    }
    
    // 检测按钮是否靠近边界并自动收缩
    function checkEdgeAndHide() {
        // 只有用户拖动过按钮（有自定义位置）才启用边界隐藏
        if (!hasCustomPosition) return;
        
        const rect = aiAssistantBtn.getBoundingClientRect();
        const threshold = 60; // 边界阈值
        
        // 移除所有边界类
        aiAssistantBtn.classList.remove('edge-left', 'edge-right', 'edge-top', 'edge-bottom', 'expanded');
        
        // 检测靠近哪个边界
        if (rect.left < threshold) {
            aiAssistantBtn.classList.add('edge-left');
        } else if (rect.right > window.innerWidth - threshold) {
            aiAssistantBtn.classList.add('edge-right');
        } else if (rect.top < threshold) {
            aiAssistantBtn.classList.add('edge-top');
        } else if (rect.bottom > window.innerHeight - threshold) {
            aiAssistantBtn.classList.add('edge-bottom');
        }
    }
    
    // 展开按钮
    function expandButton() {
        aiAssistantBtn.classList.add('expanded');
        // 清除自动隐藏定时器
        if (autoHideTimer) {
            clearTimeout(autoHideTimer);
        }
        // 3秒后自动收缩
        autoHideTimer = setTimeout(() => {
            aiAssistantBtn.classList.remove('expanded');
        }, 3000);
    }
    
    // 鼠标悬停时展开
    aiAssistantBtn.addEventListener('mouseenter', function() {
        if (aiAssistantBtn.classList.contains('edge-left') || 
            aiAssistantBtn.classList.contains('edge-right') ||
            aiAssistantBtn.classList.contains('edge-top') ||
            aiAssistantBtn.classList.contains('edge-bottom')) {
            expandButton();
        }
    });
    
    // 鼠标按下
    aiAssistantBtn.addEventListener('mousedown', function(e) {
        // 只有左键才能拖动
        if (e.button !== 0) return;
        
        // 如果在边界收缩状态，先展开
        if (aiAssistantBtn.classList.contains('edge-left') || 
            aiAssistantBtn.classList.contains('edge-right') ||
            aiAssistantBtn.classList.contains('edge-top') ||
            aiAssistantBtn.classList.contains('edge-bottom')) {
            expandButton();
        }
        
        isDragging = false; // 初始为false，移动后才设为true
        aiAssistantBtn.classList.add('dragging');
        
        const rect = aiAssistantBtn.getBoundingClientRect();
        startX = e.clientX;
        startY = e.clientY;
        initialLeft = rect.left;
        initialTop = rect.top;
        
        e.preventDefault();
    });
    
    // 鼠标移动
    document.addEventListener('mousemove', function(e) {
        if (!aiAssistantBtn.classList.contains('dragging')) return;
        
        const deltaX = e.clientX - startX;
        const deltaY = e.clientY - startY;
        
        // 如果移动距离超过5px，才认为是拖动
        if (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5) {
            isDragging = true;
            // 拖动时移除边界状态
            aiAssistantBtn.classList.remove('edge-left', 'edge-right', 'edge-top', 'edge-bottom', 'expanded');
        }
        
        if (isDragging) {
            let newLeft = initialLeft + deltaX;
            let newTop = initialTop + deltaY;
            
            // 边界限制
            const btnWidth = aiAssistantBtn.offsetWidth;
            const btnHeight = aiAssistantBtn.offsetHeight;
            newLeft = Math.max(0, Math.min(newLeft, window.innerWidth - btnWidth));
            newTop = Math.max(0, Math.min(newTop, window.innerHeight - btnHeight));
            
            aiAssistantBtn.style.left = newLeft + 'px';
            aiAssistantBtn.style.top = newTop + 'px';
            aiAssistantBtn.style.right = 'auto';
            aiAssistantBtn.style.bottom = 'auto';
        }
    });
    
    // 鼠标释放
    document.addEventListener('mouseup', function() {
        if (aiAssistantBtn.classList.contains('dragging')) {
            aiAssistantBtn.classList.remove('dragging');
            
            // 保存位置
            if (isDragging) {
                const position = {
                    left: aiAssistantBtn.style.left,
                    top: aiAssistantBtn.style.top
                };
                localStorage.setItem('aiAssistantBtnPosition', JSON.stringify(position));
                hasCustomPosition = true; // 标记为已自定义位置
                
                // 拖动结束后检查是否需要收缩
                setTimeout(() => checkEdgeAndHide(), 300);
            } else {
                // 如果没有拖动，则是点击事件
                aiChatPanel.classList.toggle('active');
                if (aiChatPanel.classList.contains('active')) {
                    aiChatInput.focus();
                    // 打开对话框时保持展开
                    expandButton();
                }
            }
            
            isDragging = false;
        }
    });
    
    // 窗口大小变化时重新检查
    window.addEventListener('resize', function() {
        setTimeout(() => checkEdgeAndHide(), 100);
    });
}

// 关闭AI助手面板
if (aiCloseBtn) {
    aiCloseBtn.addEventListener('click', function() {
        aiChatPanel.classList.remove('active');
    });
}

// 发送消息
if (aiSendBtn) {
    aiSendBtn.addEventListener('click', sendAIMessage);
}

// 回车发送（Shift+Enter换行）
if (aiChatInput) {
    aiChatInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendAIMessage();
        }
    });
}

// 发送AI消息（流式输出）
async function sendAIMessage() {
    const message = aiChatInput.value.trim();
    if (!message) return;
    
    // 显示用户消息
    addAIMessage(message, 'user');
    aiChatInput.value = '';
    
    // 禁用发送按钮
    aiSendBtn.disabled = true;
    aiSendBtn.innerHTML = '<span class="ai-loading">思考中</span>';
    
    // 创建AI消息容器
    const aiMessageDiv = document.createElement('div');
    aiMessageDiv.className = 'ai-message ai-message-assistant';
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'ai-message-content explanation-text';
    contentDiv.textContent = '';
    
    aiMessageDiv.appendChild(contentDiv);
    aiChatMessages.appendChild(aiMessageDiv);
    
    // 用于累积markdown内容
    let markdownContent = '';
    
    // 渲染markdown内容的函数
    function renderMarkdown(content) {
        if (typeof marked !== 'undefined') {
            try {
                // 使用marked.js渲染markdown
                const html = marked.parse(content);
                contentDiv.innerHTML = html;
                
                // 渲染数学公式（KaTeX）- 使用防抖避免重复渲染
                if (typeof renderMathInElement !== 'undefined') {
                    // 清除之前的渲染定时器
                    if (window.latexRenderTimer) {
                        clearTimeout(window.latexRenderTimer);
                    }
                    
                    // 延迟渲染，避免流式输出中的频繁重复渲染
                    window.latexRenderTimer = setTimeout(() => {
                        try {
                            console.log('正在渲染LaTeX公式...');
                            renderMathInElement(contentDiv, {
                                delimiters: [
                                    {left: '$$', right: '$$', display: true},
                                    {left: '$', right: '$', display: false},
                                    {left: '\\[', right: '\\]', display: true},
                                    {left: '\\(', right: '\\)', display: false}
                                ],
                                throwOnError: false,
                                errorColor: '#cc0000'
                            });
                            console.log('LaTeX公式渲染完成');
                        } catch (e) {
                            console.error('LaTeX渲染错误:', e);
                        }
                    }, 100); // 100ms延迟，等待流式输出稳定
                } else {
                    console.warn('KaTeX renderMathInElement 函数未找到');
                }
            } catch (e) {
                console.error('Markdown渲染错误:', e);
                contentDiv.textContent = content;
            }
        } else {
            // 如果没有marked.js，使用纯文本
            contentDiv.textContent = content;
        }
    }
    
    try {
        // 获取选择的AI服务
        const aiService = document.getElementById('aiServiceSelector').value;
        
        const response = await fetch('/api/ai/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 
                message: message,
                service: aiService 
            })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        // 读取流式响应
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        
        while (true) {
            const { done, value } = await reader.read();
            
            if (done) break;
            
            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split('\n');
            buffer = lines.pop() || ''; // 保留不完整的行
            
            for (const line of lines) {
                if (line.startsWith('data: ')) {
                    const data = line.slice(6);
                    if (data === '[DONE]') {
                        break;
                    }
                    
                    try {
                        const parsed = JSON.parse(data);
                        if (parsed.content) {
                            markdownContent += parsed.content;
                            // 实时渲染markdown
                            renderMarkdown(markdownContent);
                            // 滚动到底部
                            aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
                        } else if (parsed.error) {
                            contentDiv.textContent = '抱歉，AI服务暂时不可用：' + parsed.error;
                        }
                    } catch (e) {
                        console.error('解析流数据错误:', e);
                    }
                }
            }
        }
        
        // 如果没有内容，显示错误
        if (!markdownContent.trim()) {
            contentDiv.textContent = '抱歉，我现在无法回答。请稍后再试。';
        } else {
            // 最后再渲染一次，确保完整显示
            renderMarkdown(markdownContent);
        }
        
    } catch (error) {
        console.error('AI对话错误:', error);
        contentDiv.textContent = '网络错误，请检查连接后重试。';
    } finally {
        // 恢复发送按钮
        aiSendBtn.disabled = false;
        aiSendBtn.textContent = '发送';
    }
}

// 添加消息到对话框
function addAIMessage(content, role) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `ai-message ai-message-${role}`;
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'ai-message-content' + (role === 'assistant' ? ' explanation-text' : '');
    
    // 如果是AI助手消息，使用markdown渲染；用户消息保持纯文本
    if (role === 'assistant' && typeof marked !== 'undefined') {
        contentDiv.innerHTML = marked.parse(content);
        // 渲染数学公式
        if (typeof renderMathInElement !== 'undefined') {
            renderMathInElement(contentDiv, {
                delimiters: [
                    {left: '$$', right: '$$', display: true},
                    {left: '$', right: '$', display: false},
                    {left: '\\[', right: '\\]', display: true},
                    {left: '\\(', right: '\\)', display: false}
                ]
            });
        }
    } else {
        contentDiv.textContent = content;
    }
    
    messageDiv.appendChild(contentDiv);
    aiChatMessages.appendChild(messageDiv);
    
    // 滚动到底部
    aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('答题页面已加载');
    
    // 获取分类参数
    const urlParams = new URLSearchParams(window.location.search);
    const category = urlParams.get('category') || '';
    
    // 更新分类显示
    if (category) {
        const categoryElement = document.getElementById('quizCategory');
        if (categoryElement) {
            categoryElement.textContent = category;
        }
    }
    
    // 从服务器加载题目
    loadQuestionsFromServer(category);
    
    // 绑定事件
    bindEvents();
    
    // 启动计时器
    startTimer();
    
    // 显示答题按钮（因为PC端直接进入答题页面）
    const quizActions = document.querySelector('.quiz-actions');
    if (quizActions) {
        quizActions.classList.add('active');
    }
});

// 加载题目
function loadQuestion() {
    const question = questions[currentQuestionIndex];
    if (!question) return;
    
    // 更新进度条
    const progress = ((currentQuestionIndex + 1) / questions.length) * 100;
    document.getElementById('progressBar').style.width = progress + '%';
    
    // 更新题目计数器
    document.getElementById('currentQuestion').textContent = currentQuestionIndex + 1;
    document.getElementById('totalQuestions').textContent = questions.length;
    
    // 显示题目（支持markdown和数学公式）
    const questionTitleEl = document.getElementById('questionTitle');
    questionTitleEl.innerHTML = renderMarkdown(question.title);
    
    // 渲染数学公式
    renderMath(questionTitleEl);
    
    // 显示题目图片
    const questionImageContainer = questionTitleEl.parentElement;
    const existingImage = questionImageContainer.querySelector('.question-image');
    if (existingImage) existingImage.remove();
    
    if (question.question_image) {
        const img = document.createElement('img');
        img.src = question.question_image;
        img.className = 'question-image';
        img.alt = '题目配图';
        questionTitleEl.after(img);
    }
    
    // 生成选项或填空输入框
    const optionsContainer = document.getElementById('questionOptions');
    optionsContainer.innerHTML = '';
    
    if (question.question_type === 'fill_in_blank') {
        // 填空题界面
        const fillInContainer = document.createElement('div');
        fillInContainer.className = 'fill-in-container';
        
        const fillInLabel = document.createElement('label');
        fillInLabel.className = 'fill-in-label';
        fillInLabel.textContent = '请输入答案：';
        
        const fillInInput = document.createElement('input');
        fillInInput.type = 'text';
        fillInInput.className = 'fill-in-input';
        fillInInput.placeholder = '请输入你的答案';
        fillInInput.id = 'fillInInput';
        
        // 如果已经有答案，显示之前的输入
        if (userAnswers[currentQuestionIndex] !== undefined) {
            fillInInput.value = userAnswers[currentQuestionIndex];
            fillInInput.disabled = true; // 已答题后禁用输入
        } else {
            fillInInput.addEventListener('input', function() {
                userAnswers[currentQuestionIndex] = this.value;
                updateButtonStates();
            });
        }
        
        fillInContainer.appendChild(fillInLabel);
        fillInContainer.appendChild(fillInInput);
        optionsContainer.appendChild(fillInContainer);
    } else {
        // 选择题界面
        question.options.forEach((option, index) => {
        const optionElement = document.createElement('div');
        optionElement.className = 'option-item';
        
        // 如果已经回答过，显示正确答案
        if (userAnswers[currentQuestionIndex] !== undefined) {
            const selectedIndex = userAnswers[currentQuestionIndex];
            if (index === question.correct) {
                optionElement.classList.add('correct');
            }
            if (index === selectedIndex && selectedIndex !== question.correct) {
                optionElement.classList.add('incorrect');
            }
        } else {
            optionElement.setAttribute('data-index', index);
            optionElement.addEventListener('click', function() {
                selectOption(index);
            });
        }
        
        const optionLabel = document.createElement('span');
        optionLabel.className = 'option-label';
        optionLabel.textContent = String.fromCharCode(65 + index) + '.';
        
        const optionContent = document.createElement('div');
        optionContent.className = 'option-content';
        
        const optionText = document.createElement('span');
        optionText.className = 'option-text';
        optionText.innerHTML = renderMarkdown(option);
        optionContent.appendChild(optionText);
        
        // 渲染选项中的数学公式
        renderMath(optionText);
        
        // 显示选项图片
        const imageKey = ['option_a_image', 'option_b_image', 'option_c_image', 'option_d_image'][index];
        if (question[imageKey]) {
            const optionImg = document.createElement('img');
            optionImg.src = question[imageKey];
            optionImg.className = 'option-image';
            optionImg.alt = `选项${String.fromCharCode(65 + index)}配图`;
            optionContent.appendChild(optionImg);
        }
        
        optionElement.appendChild(optionLabel);
        optionElement.appendChild(optionContent);
        
        optionsContainer.appendChild(optionElement);
        });
    }
    
    // 更新按钮状态
    updateButtonStates();
}

// 选择选项
function selectOption(index) {
    userAnswers[currentQuestionIndex] = index;
    
    // 更新选项显示
    document.querySelectorAll('.option-item').forEach((item, idx) => {
        item.classList.remove('selected');
        if (idx === index) {
            item.classList.add('selected');
        }
    });
    
    // 如果答对了，自动进入下一题（可选）
    // setTimeout(() => {
    //     if (currentQuestionIndex < questions.length - 1) {
    //         nextQuestion();
    //     }
    // }, 1000);
}

// 上一题
function prevQuestion() {
    if (currentQuestionIndex > 0) {
        currentQuestionIndex--;
        loadQuestion();
        
        // 如果是已经答过的题目，显示之前的答案
        if (userAnswers[currentQuestionIndex] !== undefined) {
            const selectedIndex = userAnswers[currentQuestionIndex];
            const options = document.querySelectorAll('.option-item');
            options.forEach((item, idx) => {
                if (idx === selectedIndex) {
                    item.classList.add('selected');
                }
            });
        }
    }
}

// 下一题
function nextQuestion() {
    if (currentQuestionIndex < questions.length - 1) {
        currentQuestionIndex++;
        loadQuestion();
    }
}

// 更新按钮状态
function updateButtonStates() {
    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');
    const submitBtn = document.getElementById('submitBtn');
    
    // 上一题按钮
    prevBtn.disabled = currentQuestionIndex === 0;
    
    // 最后一题显示提交按钮
    if (currentQuestionIndex === questions.length - 1) {
        nextBtn.style.display = 'none';
        submitBtn.style.display = 'block';
    } else {
        nextBtn.style.display = 'block';
        submitBtn.style.display = 'none';
    }
}

// 填空题答案检查函数
function checkFillInAnswer(userAnswer, correctAnswer, keywords = '') {
    if (!userAnswer || !correctAnswer) {
        return false;
    }
    
    // 清理用户答案
    userAnswer = userAnswer.trim().toLowerCase();
    
    // 处理多个正确答案（用逗号分隔）
    const correctAnswers = correctAnswer.split(',').map(ans => ans.trim().toLowerCase());
    
    // 处理关键词（用逗号分隔）
    const keywordList = keywords ? keywords.split(',').map(kw => kw.trim().toLowerCase()) : [];
    
    // 检查是否匹配正确答案
    if (correctAnswers.includes(userAnswer)) {
        return true;
    }
    
    // 检查是否匹配关键词
    if (keywordList.includes(userAnswer)) {
        return true;
    }
    
    // 模糊匹配（去除空格、标点符号）
    const userClean = userAnswer.replace(/[^\w\u4e00-\u9fff]/g, '');
    
    for (const ans of correctAnswers) {
        const ansClean = ans.replace(/[^\w\u4e00-\u9fff]/g, '');
        if (userClean === ansClean) {
            return true;
        }
    }
    
    for (const kw of keywordList) {
        const kwClean = kw.replace(/[^\w\u4e00-\u9fff]/g, '');
        if (userClean === kwClean) {
            return true;
        }
    }
    
    return false;
}

// 提交答案
function submitQuiz() {
    // 确认是否提交
    if (userAnswers.length < questions.length) {
        const confirmed = confirm(`您还有 ${questions.length - userAnswers.length} 题未作答，确定提交吗？`);
        if (!confirmed) return;
    }
    
    // 停止计时器
    clearInterval(timerInterval);
    
    // 计算成绩
    let correctCount = 0;
    let wrongCount = 0;
    
    for (let i = 0; i < questions.length; i++) {
        const question = questions[i];
        const userAnswer = userAnswers[i];
        
        if (question.question_type === 'fill_in_blank') {
            // 填空题答案检查
            if (checkFillInAnswer(userAnswer, question.fill_in_answer, question.fill_in_keywords)) {
                correctCount++;
            } else {
                wrongCount++;
            }
        } else {
            // 选择题答案检查
            if (userAnswer === question.correct) {
                correctCount++;
            } else {
                wrongCount++;
            }
        }
    }
    
    const score = Math.round((correctCount / questions.length) * 100);
    
    // 显示结果
    showResult(correctCount, wrongCount, score);
    
    // 准备填空题答案数组
    const fillInAnswers = [];
    for (let i = 0; i < questions.length; i++) {
        if (questions[i].question_type === 'fill_in_blank') {
            fillInAnswers.push(userAnswers[i] || '');
        } else {
            fillInAnswers.push('');
        }
    }
    
    // 保存成绩到数据库（包含详细题目和答案数据）
    saveQuizResult({
        category: getCurrentCategory(),
        correctCount: correctCount,
        wrongCount: wrongCount,
        score: score,
        timeElapsed: timeElapsed,
        questions: questions,
        userAnswers: userAnswers,
        fillInAnswers: fillInAnswers
    });
}

// 显示结果
function showResult(correctCount, wrongCount, score) {
    document.getElementById('correctCount').textContent = correctCount;
    document.getElementById('wrongCount').textContent = wrongCount;
    document.getElementById('score').textContent = score;
    
    let message = '';
    if (score >= 90) {
        message = '恭喜！您的表现非常出色！🌟';
    } else if (score >= 70) {
        message = '不错！继续加油！💪';
    } else if (score >= 60) {
        message = '还可以更好，继续努力！📚';
    } else {
        message = '需要加强学习，不要气馁！💪';
    }
    
    document.getElementById('resultMessage').textContent = message;
    
    // 保存详细数据到 sessionStorage 供详情页使用
    const quizResult = {
        correctCount: correctCount,
        wrongCount: wrongCount,
        score: score,
        timeElapsed: timeElapsed,
        questions: questions,
        userAnswers: userAnswers,
        category: getCurrentCategory()
    };
    sessionStorage.setItem('quizResult', JSON.stringify(quizResult));
    
    // 显示结果弹窗
    const resultModal = document.getElementById('resultModal');
    resultModal.classList.add('show');
}

// 绑定事件
function bindEvents() {
    document.getElementById('prevBtn').addEventListener('click', prevQuestion);
    document.getElementById('nextBtn').addEventListener('click', nextQuestion);
    document.getElementById('submitBtn').addEventListener('click', submitQuiz);
    
    document.getElementById('reviewBtn').addEventListener('click', function() {
        // 跳转到答题详情页
        window.location.href = '/quiz-detail';
    });
    
    document.getElementById('backHomeBtn').addEventListener('click', function() {
        window.location.href = '/';
    });
}

// 启动计时器
function startTimer() {
    timerInterval = setInterval(function() {
        timeElapsed++;
        
        const minutes = Math.floor(timeElapsed / 60);
        const seconds = timeElapsed % 60;
        
        const timeString = 
            String(minutes).padStart(2, '0') + ':' + 
            String(seconds).padStart(2, '0');
        
        document.getElementById('timerText').textContent = timeString;
    }, 1000);
}

// 保存答题结果到数据库
async function saveQuizResult(result) {
    try {
        console.log('准备保存答题结果:', result);
        
        const response = await fetch('/api/save-quiz-result', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(result)
        });
        
        const data = await response.json();
        
        if (data.success) {
            console.log('[OK] 答题结果已保存到数据库:', data.message);
        } else {
            console.error('[ERROR] 保存失败:', data.error || data.message);
        }
    } catch (error) {
        console.error('[ERROR] 保存答题结果失败:', error);
    }
}

// 获取当前题库分类（示例）
function getCurrentCategory() {
    const categoryElement = document.getElementById('quizCategory');
    return categoryElement ? categoryElement.textContent : '综合知识';
}

// 从服务器加载题目
async function loadQuestionsFromServer(category) {
    try {
        showLoading();
        console.log('开始从服务器加载题目，分类:', category);
        const response = await fetch(`/api/get-questions?category=${encodeURIComponent(category)}`);
        const data = await response.json();
        
        console.log('收到服务器响应:', data);
        
        if (data.success && data.questions) {
            // 后端已经返回正确格式，直接使用
            questions = data.questions;
            
            console.log(`✅ 成功加载 ${questions.length} 道题目`);
            console.log('第一题:', questions[0]);
            
            hideLoading();
            loadQuestion();
        } else {
            console.error('加载失败:', data.error || data.message);
            hideLoading();
            alert('加载题目失败: ' + (data.error || '未知错误'));
        }
    } catch (error) {
        console.error('加载题目失败:', error);
        hideLoading();
        alert('网络错误，请检查连接后重试: ' + error.message);
    }
}

// 显示加载中
function showLoading() {
    document.getElementById('questionTitle').textContent = '题目加载中...';
    document.getElementById('questionOptions').innerHTML = '';
}

// 隐藏加载中
function hideLoading() {
    // 内容将由loadQuestion()填充
}

